/**
 * @file 复合BoxGroup组件
 * @author maoquan(maoquan@baidu.com)
 */

define(
    function (require) {
        var u = require('underscore');
        var InputControl = require('esui/InputControl');
        var eoo = require('eoo');
        var esui = require('esui/main');
        var lib = require('esui/lib');
        var painters = require('esui/painters');

        require('./extension/RadioTab');
        require('esui/BoxGroup');

        var TPL = require('text!./tpl/compositeboxgroup.tpl.html');

        /**
         * CompositeBoxGroup类定义。
         *
         * @class
         * @extends Control
         *
         * @constructor
         *
         * 创建新的CompositeBoxGroup实例。
         *
         * @param {Object} [options] 组件参数。
         */
        var CompositeBoxGroup = eoo.create(
            InputControl,
            {
                /**
                 * CompositeBoxGroup类型。用于注册到ESUI库。
                 *
                 * @override
                 */
                type: 'CompositeBoxGroup',

                /**
                 * 初始化传入参数。
                 *
                 * @param {Object} options 初始化参数
                 * @override
                 */
                initOptions: function (options) {
                    var properties = {
                        outerBoxType: 'radio',
                        outerBoxClass: 'ui-radio-custom',
                        otherLabel: '请选择',
                        allText: '不限',
                        allValue: 'ALL'
                    };
                    u.extend(properties, options);

                    // 应用场景为：第一层选项为`不限`和`其他`（互斥），其中点`其他`,展开子项，子项可多选
                    // 如果数据源为[{'不限'}, {'选项1'}, {'选项2'}, ...],需转化为[{'不限'}, {'其他',chidlren:['选项1', '选项2']}]
                    // 这里要为自动生成的其他选项添加一个id，以便在子项展开，获取控件值时使用
                    properties.otherValue = lib.getGUID('OTHER');

                    this.$super([properties]);
                },

                /**
                 * @override
                 */
                initStructure: function () {
                    this.main.innerHTML = lib.format(
                        TPL,
                        {
                            outername: this.name,
                            outerId: this.helper.getId('outer'),
                            outerBoxType: this.outerBoxType,
                            outerBoxClass: this.outerBoxClass
                        }
                    );
                    var controls = esui.init(this.main);
                    this.outerBoxGroup = controls[0];
                },

                /**
                 * @override
                 */
                initEvents: function () {
                },

                /**
                 * 重渲染
                 *
                 * @method
                 * @protected
                 * @override
                 */
                repaint: painters.createRepaint(
                    InputControl.prototype.repaint,
                    {
                        name: 'datasource',
                        paint: function (me, datasource) {
                            if (!datasource || !datasource.length) {
                                return;
                            }
                            var firstItem = datasource[0];
                            if (firstItem.value === me.allValue) {
                                var otherDatasource = {
                                    id: me.otherValue,
                                    text: me.otherLabel,
                                    value: me.otherValue,
                                    children: datasource.slice(1)
                                };
                                datasource = [
                                    datasource[0],
                                    otherDatasource
                                ];
                            }
                            me.outerBoxGroup.setProperties({datasource: datasource});

                            u.each(
                                datasource,
                                function (item, key) {
                                    if (!item.children || !item.children.length) {
                                        return;
                                    }
                                    var panel = document.createElement('div');
                                    item.id = item.id || item.value;
                                    panel.id = item.id + '-panel';
                                    me.main.appendChild(panel);
                                    var options = {
                                        datasource: item.children,
                                        boxType: item.boxType || 'checkbox',
                                        boxClass: item.boxClass || 'ui-checkbox-custom'
                                    };
                                    var boxGroup = esui.create('BoxGroup', options);
                                    boxGroup.appendTo(panel);
                                    me.addChild(boxGroup, item.id);
                                }
                            );
                        }
                    },
                    {
                        name: 'rawValue',
                        paint: function (me, rawValue) {
                            if (!rawValue || !rawValue.length) {
                                return;
                            }
                            var datasource = me.outerBoxGroup.get('datasource');
                            var allValues = u.map(
                                datasource,
                                function (item) {
                                    return item.value;
                                }
                            );
                            // 如果传入值是`不限` / 或者在第一层选项中, 直接选择第一级的选项
                            if (rawValue[0] === me.allValue
                                || (rawValue.length === 1 && u.contains(allValues, rawValue[0]))) {
                                me.outerBoxGroup.setProperties({rawValue: rawValue});
                            }
                            // 否则向下查找子项
                            else {
                                var checkedItem = u.find(
                                    datasource,
                                    function (item) {
                                        if (item.children && item.children.length >= rawValue.length) {
                                            var childValues = u.map(
                                                item.children,
                                                function (childItem) {
                                                    return childItem.value;
                                                }
                                            );
                                            var intersection = u.intersection(childValues, rawValue);
                                            if (intersection.length === rawValue.length) {
                                                return true;
                                            }
                                        }
                                        return false;
                                    }
                                );
                            }
                            if (checkedItem) {
                                me.outerBoxGroup.setProperties(
                                    {
                                        rawValue: [checkedItem.value]
                                    }
                                );
                                var childBoxGroup = me.getChild(checkedItem.value);
                                if (childBoxGroup) {
                                    childBoxGroup.setProperties(
                                        {
                                            rawValue: rawValue
                                        }
                                    );
                                }
                            }
                        }
                    }
                ),

                getRawValue: function () {
                    var outerValue = this.outerBoxGroup.getValue();
                    var datasource = this.outerBoxGroup.get('datasource');
                    var allValues = u.map(
                        datasource,
                        function (item) {
                            return item.value;
                        }
                    );
                    var childBoxGroup = this.getChild(outerValue);
                    if (childBoxGroup) {
                        return childBoxGroup.getRawValue();
                    }
                    else if (u.contains(allValues, outerValue) && outerValue !== this.otherValue) {
                        return [outerValue];
                    }

                    return [];
                },

                getValue: function () {
                    var rawValue = this.getRawValue();
                    return rawValue.join(',');
                },

                /**
                 * 将字符串类型的值转换成原始格式
                 *
                 * @param {string} value 字符串值
                 * @return {string[]}
                 * @protected
                 * @override
                 */
                parseValue: function (value) {
                    if (u.isString(value)) {
                        return value.split(',');
                    }
                    return value;
                },

                /**
                 * @override
                 */
                dispose: function () {
                    this.$super(arguments);

                    if (this.helper.isInStage('DISPOSED')) {
                        return;
                    }
                }
            }
        );

        esui.register(CompositeBoxGroup);
        return CompositeBoxGroup;
    }
);
